package Send2ME::RulePage;

use Dancer ':syntax';

use UUID::Tiny;

use Send2ME::Dao::Auth;
use Send2ME::Dao::Rule;

prefix '/rule';

get '/' => sub {
	unless (credential->{logged_in}) {
		redirect '/';
		return;
	}
	
	my $rule_uuid = undef;
	my $rule_hash = undef;
	
	if (params->{uuid}) {
		$rule_uuid = params->{uuid};
		$rule_hash = session($rule_uuid);	
	} else {
		$rule_uuid = create_UUID_as_string();
	}
	
	if (params->{id}) {
		my $rule = getRule({id => params->{id}});
		
		if ($rule->{user_id} ne credential->{user}->{id}) {
			redirect "/";
			return;
		}
		
		if ($rule) {
			$rule_hash->{rule_id} 			= $rule->{id};
			$rule_hash->{rule_name} 		= $rule->{name};
			$rule_hash->{rule_conditions} 	= $rule->{conditions};
			$rule_hash->{rule_route_in} 	= $rule->{route_in};
			$rule_hash->{rule_routes} 		= $rule->{routes};
		}
	}
	
	my @predefined = getPredefinedRules();
	
	template 'rule-page', {
		rule_uuid => $rule_uuid,
		rule_hash => $rule_hash,
		templates => \@predefined
	};
};

1;